package com.newtribe.net;

import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
/**
 * <p>Title: iAuth Project</p>
 * <p>Description: </p>
 * <p>Copyright:   GFA E-Commerce Security CA Co., Ltd. Copyright (c) 2006</p>
 * <p>Company: 国富安公司</p>
 * @author fuwei, fuwei@ec.com.cn
 * @version 1.0
 */

public class HttpClient {
	
	private String serverAddress ;
	private String auth  ;
  public HttpClient(String server) {
	  this.serverAddress =server ;
  }
  public static void main(String[] args) throws Exception{
	  
	  HttpClient client =new HttpClient("http://211.88.25.33:8081/cross/xmlstore.action") ;
	  
	  
	  
//	  boolean auth =client.auth();
//	  if (auth ) {
//		  //user auth passed
//		  Map<String,String> clientInfo =new HashMap<String,String>() ;
//		  clientInfo.put("udp_port", String.valueOf(8911)) ;
//		  client.sendinfo(clientInfo) ;
//	  }
	  
  }
  
  
  public  boolean  auth() throws Exception{


   URL url =new URL(serverAddress) ;
  

   System.out.println("connect ..." +url);

   HttpURLConnection conn =( HttpURLConnection) url.openConnection() ;
   addCommonHeader(conn);
   conn.addRequestProperty("helo" ,url.getHost());
   conn.addRequestProperty("user" ,"fuwei");
   conn.addRequestProperty("type","init");
   conn.connect();
   
   Map headers  =conn.getHeaderFields();
   System.out.println(headers);
   
    auth = conn.getHeaderField("auth");
   
   return auth!=null ;
 //////////////////////////////////////////


  }
  
  public  Map  sendinfo(Map<String ,String> clientInfo) throws Exception{
	   URL url =new URL(serverAddress) ;
	   System.out.println("connect ..." +url);

	   HttpURLConnection conn =( HttpURLConnection) url.openConnection() ;
	   addCommonHeader(conn);
	   conn.addRequestProperty("helo" ,url.getHost());
	   conn.addRequestProperty("auth" ,this.auth);
	   conn.addRequestProperty("type","init");
	   Iterator iter =clientInfo.keySet().iterator();
	   
	   while (iter.hasNext()){
		   String key =(String)iter.next();
		   String value=clientInfo.get(key) ;
		   conn.addRequestProperty(key, value) ;
		   
	   }
	   conn.connect();
	   
	   Map headers  =conn.getHeaderFields();
	   System.out.println(headers);
	   
	   return headers ;
	 //////////////////////////////////////////


	  }
  
  public void addCommonHeader(HttpURLConnection conn){
	   conn.addRequestProperty("user-agent" ,"rdp2p1.2");

	}

}
